/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.rpc.syncUser.user;

import com.je.common.base.DynaBean;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.service.MetaService;
import com.je.common.base.util.DateUtils;
import com.je.common.base.util.JEUUID;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.exception.RoleException;
import com.je.rbac.model.syncdata.SyncRole;
import com.je.rbac.rpc.SyncRoleDataRpcService;
import com.je.rbac.rpc.syncUser.util.StreamEx;
import com.je.rbac.rpc.syncUser.util.SyncParserUserUtil;
import com.je.rbac.service.IconType;
import org.apache.servicecomb.provider.pojo.RpcSchema;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.je.rbac.service.role.impl.RbacRoleServiceImpl.ROLE_TYPE_CODE;
import static com.je.rbac.service.role.impl.RbacRoleServiceImpl.ROLE_TYPE_NAME;

@RpcSchema(schemaId = "syncRoleDataRpcService")
public class SyncRoleDataRpcServiceImpl implements SyncRoleDataRpcService {
    @Autowired
    private MetaService metaService;

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, RoleException.class})
    public BaseRespResult syncRoleData(List<SyncRole> roleData) {
        //拿到所有角色数据先插入最顶级数据，然后递归插入子节点数据
        try {
            if(StreamEx.checkCFNumByRoleId(roleData)>0){
                return BaseRespResult.errorResult("JE_RBAC_ROLE_ID 主键字段重复，请检查！");
            }
            if(roleData == null || roleData.size()==0){
                return BaseRespResult.errorResult("角色数据为空，请检查！");
            }
            for(SyncRole eachSyncBean : roleData){
                    DynaBean eachBean = buildDynaBean(eachSyncBean);
                    DynaBean bean = metaService.selectOne("JE_RBAC_ROLE", ConditionsWrapper.builder().eq("JE_RBAC_ROLE_ID",eachBean.getStr("JE_RBAC_ROLE_ID")));
                    if(bean == null){
                        insertRole(eachBean);
                    }else{
                        //如果存在，则更新数据基本信息
                        updateRoleBasicInfo(eachBean);
                    }
            }
        } catch (Exception e) {
            return BaseRespResult.errorResult(e.getMessage());
        }
        return BaseRespResult.successResult("操作成功！");
    }

    @Transactional(rollbackFor = {RuntimeException.class, RoleException.class})
    public void updateRoleBasicInfo(DynaBean dynaBean){
        metaService.executeSql("UPDATE JE_RBAC_ROLE SET ROLE_NAME={0} WHERE JE_RBAC_ROLE_ID={1}",
                dynaBean.getStr("ROLE_NAME"),dynaBean.getStr("JE_RBAC_ROLE_ID"));
    }

    @Transactional(rollbackFor = {RuntimeException.class, RoleException.class})
    public DynaBean insertRole(DynaBean dynaBean) throws RoleException {
        List<Map<String, Object>> countList = metaService.selectSql("SELECT MAX(SY_ORDERINDEX) AS MAX_COUNT FROM JE_RBAC_ROLE");
        int count = (int) countList.get(0).get("MAX_COUNT");
        DynaBean parent = metaService.selectOne("JE_RBAC_ROLE", ConditionsWrapper.builder().eq("JE_RBAC_ROLE_ID", "ROOT"));
        if (parent == null) {
            throw new RoleException("不存在的父角色，请确认父角色存在！");
        }
        List<Map<String, Object>> currentChildList = metaService.selectSql("SELECT COUNT(*) AS TOTAL_COUNT FROM JE_RBAC_ROLE WHERE SY_PARENT = {0}", "ROOT");
        long currentChildCount = (long) currentChildList.get(0).get("TOTAL_COUNT");
        String roleId = JEUUID.uuid();
        DynaBean roleBean = new DynaBean("JE_RBAC_ROLE", false);
        roleBean.set("JE_RBAC_ROLE_ID", dynaBean.getStr("JE_RBAC_ROLE_ID"));
        roleBean.set("ROLE_NAME", dynaBean.getStr("ROLE_NAME"));
        roleBean.set("ROLE_CODE", "role-" + String.format("%06d", count + 1));
        roleBean.set("ROLE_TYPE_CODE", ROLE_TYPE_CODE);
        roleBean.set("ROLE_TYPE_NAME", ROLE_TYPE_NAME);
        roleBean.set("ROLE_ICONCLS", IconType.TCONTYPE_ROLE.getVal());

        //树形节点值
        roleBean.set("SY_PARENT", parent.getStr("JE_RBAC_ROLE_ID"));
        roleBean.set("SY_PARENTPATH", parent.getStr("SY_PATH"));
        roleBean.set("SY_LAYER", parent.getInt("SY_LAYER") + 1);
        roleBean.set("SY_STATUS", "1");
        roleBean.set("SY_NODETYPE", "LEAF");
        roleBean.set("SY_PATH", parent.getStr("SY_PATH") + "/" + roleId);
        roleBean.set("SY_TREEORDERINDEX", parent.getStr("SY_TREEORDERINDEX") + String.format("%06d", currentChildCount + 1));
        //创建时间
        roleBean.set("SY_CREATETIME", DateUtils.formatDateTime(new Date()));
        roleBean.set("ROLE_DEVELOP", "0");
        roleBean.set("SY_ORDERINDEX", count + 1);
        metaService.insert(roleBean);
        return roleBean;
    }

    /***
     *构建角色数据 基本信息
     * @param beanMap
     * @return
     * @throws RoleException
     */
    public  DynaBean buildDynaBean(SyncRole beanMap) throws Exception {
        DynaBean dynaBean = new DynaBean("JE_RBAC_ROLE",false);
        dynaBean.setStr("JE_RBAC_ROLE_ID", SyncParserUserUtil.checkIsNullOrEmpty("JE_RBAC_ROLE_ID",beanMap.getRoleId()));
        dynaBean.set("SY_STATUS", "1");
        dynaBean.setStr("ROLE_NAME", SyncParserUserUtil.checkIsNullOrEmpty("ROLE_NAME",beanMap.getRoleName()));
        dynaBean.setStr("ROLE_DEVELOP", "0");
        return dynaBean;
    }

}
